import markdown
import re

class PersonPattern(markdown.inlinepatterns.Pattern):
    def handleMatch(self, m):
        el = markdown.etree.Element('a')
        el.text = m.group("text")
        if m.group("link"):
            link = m.group("link")
        else:
            link = m.group("text")
        el.set("href", "/persons/" + link)
        return el

PERSON_PATTERN = r'\(person\)\[(?P<text>.*?)\](?:\[(?P<link>.*?)\])?'
person = PersonPattern(PERSON_PATTERN)

class WorkPattern(markdown.inlinepatterns.Pattern):
    def handleMatch(self, m):
        el = markdown.etree.Element('a')
        el.text = m.group("text")
        if m.group("link"):
            link = m.group("link")
        else:
            link = m.group("text")
        el.set("href", "/works/code/"+link)
        return el
WORK_PATTERN = r'\(work\)\[(?P<text>.*?)\](?:\[(?P<link>.*?)\])?'
work = WorkPattern(WORK_PATTERN)

class TaxonPattern(markdown.inlinepatterns.Pattern):
    def handleMatch(self, m):
        el = markdown.etree.Element('a')
        el.text = m.group("text")
        if m.group("link"):
            link = m.group("link")
        else:
            link = m.group("text")
        el.set("href", "/taxons/" + link)
        return el

TAXON_PATTERN = r'\(taxon\)\[(?P<text>.*?)\](?:\[(?P<link>.*?)\])?'
taxon = TaxonPattern(TAXON_PATTERN)


class ThesaurusExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        md.registerExtension(self)
        md.inlinePatterns.add('person', person, '<reference')
        md.inlinePatterns.add('work', work, '<reference')
        md.inlinePatterns.add('taxon', taxon, '<reference')
    def reset(self):
        pass

def makeExtension(configs=None):
    return ThesaurusExtension(configs=configs)
